import { encrypt, decrypt } from "@/utils/aes";
import $ from "jquery";
/**
 * @name proxy
 * @desc 域名地址，代理前缀
 */
function proxys() {
  return {
    devProxy: "http://127.0.0.1:8080",
    testProxy: "http://127.0.0.1:8080",
    provProxy: "http://127.0.0.1:8080"
  };
}

/**
 * @name objectToSearch
 * @param {Object} value 地址栏传递内容,必须是对象类型
 * @desc 将value转化为加密字符串拼接到url后缀
 */
function objectToSearch(value) {
  if (value) {
    let encrypted = "?" + encrypt(value);
    return encrypted;
  }
}

/**
 * @name getSearchObject
 * @param {String} window.location.search
 * @desc 获取url中search参数,并转化为对象
 */
function getSearchObject() {
  let value = window.location.search.split("?");
  if (value.length > 1) {
    let str = value[1];
    let decrypted = decrypt(str);
    return decrypted;
  } else {
    return {};
  }
}
/**
 * @name randomNum
 * @param {Number} num 生成几位随机数-默认生成18位随机数
 * @param Math.random() 0-1之间的随机数
 * @param Math.floor() 向下取整
 * @description 随机数-字符串生成
 */

function randomNum(num = 18) {
  let randoms = "";
  for (let i = 0; i < Number(num); i++) {
    randoms += JSON.stringify(Math.floor(Math.random() * 10));
  }
  return randoms;
}
/**
 * @name twoDecimal
 * @param {Number} val 传入数字
 * @param {Number} len 位数-需要取小数点后几位-默认2位
 * @remake Math.round(val) 四舍五入取整
 * @remake Math.floor(val) 向下取整
 * @description 运算，取小数点后两位
 */
function twoDecimal(val = 0, len = 2) {
  let digit = Math.pow(10, len); //指数幂
  let num = Math.round(val * digit) / digit;
  return num;
}
/**
 *
 * @param {Number} num1 标准数据
 * @param {Number} num2 源数据
 * @description 计算num2是num1的最大次方
 * @returns 最大次方
 */
const power = (num1, num2) => {
  let _power = 0;
  if (num1 && num2 && typeof num1 === "number" && typeof num2 === "number" && num2 > num1) {
    //递归
    function numPower(val1, val2) {
      let _quotient = val2 / val1; //商
      if (_quotient >= val1) {
        _power += 1;
        numPower(num1, _quotient);
      }
    }
    numPower(num1, num2);
    _power += 1; //num2>num1-最初始+1
  }
  return _power;
};
/**
 * @name unitConver
 * @param {Number} val 原始大小/B(byte:字节)=8b(bit:比特位); 1字符=2字节
 * @remake B,KB,M,G,T,PB,EB,ZB,YB,BB
 * @remake Math.pow(1024, x);x=1,2,3,4,5,6,7,8,9,10
 * @return 返回相对应的大小描述
 */
function unitConver(val = 0) {
  let size = Number(val) || 0; //规范传入值
  let sizeList = ["B", "KB", "M", "G", "T", "PB", "EB", "ZB", "YB", "BB"];
  let standNum = 1024; //标准值
  let _power = power(standNum, val); //幂指
  let tag = sizeList[_power];
  size = twoDecimal(size / Math.pow(standNum, _power));
  return size + tag;
}

/**
 * @name averageArr
 * @param Array arr  原型数组
 * @param Number nums  设置每份多少个元素
 * @description 按元素个数，均分数组;一维数组转二维数组
 */
function averageArr(arr = [], nums = 1) {
  let num = arr instanceof Array ? arr.length % nums : null;
  let newArrPre = arr;
  if (num !== 0) {
    //补足arr，使其能够均分
    newArrPre = newArrPre.concat(Array(nums - num).fill(0));
  }
  //newArrPre.reduce 按补全后的数组均分
  //下方的push则是对原数组arr进行分割，则结果不会存在空元素
  let newArr = newArrPre.reduce((pre, cur, index) => {
    if ((index + 1) % nums === 0) {
      // if (pre.length === 0) {
      //   pre.push(arr.slice(0, index + 1));
      //   return pre;
      // } else {
      pre.push(arr.slice(index - (nums - 1), index + 1));
      return pre;
      // }
    } else {
      return pre;
    }
  }, []);
  return newArr;
}
/**
 * @name averageListArr
 * @param Array arr  原型数组
 * @param Number num  多少列
 * @description 按列数，均分数组;列数num，行内元素平分
 */
function averageListArr(arr = [], num, page) {
  let baseNum = Math.floor(arr.length / num); //每列元素数,向下取整
  let surNum = arr.length % num; //余数，从头分配
  let resArr = [];
  let arrNum = [];
  let totalNum = 0;
  let totalPrevNum = 0;
  // 12345
  let pageNum = page - 1; //true:;false:;

  // for (let i = 0; i < oldArr.length; i++) {
  //   oldArrIndex.push({ index: i, length: oldArr[i].length });
  // }
  // oldArrIndex = oldArrIndex.sort((a, b) => (a.length < b.length ? 1 : -1));
  console.log("按列数", num);

  //循环分配-个数
  for (let i = 0; i < num; i++) {
    if (page % 2 === 0) {
      arrNum.push(baseNum + (i >= pageNum * surNum && i < page * surNum ? 1 : 0));
    } else {
      arrNum.push(baseNum + (i < surNum ? 1 : 0));
    }
  }
  console.log("arrNum===", arrNum);
  //截取相对应个数到每一列中
  for (let j = 0; j < arrNum.length; j++) {
    totalNum += arrNum[j];
    if (j === 0) {
      resArr.push(arr.slice(j, arrNum[j]));
    } else {
      totalPrevNum += arrNum[j - 1];
      resArr.push(arr.slice(totalPrevNum, totalNum));
    }
  }
  return resArr;
}
/**
 * @name: formatNumber
 * @param {number} num
 * @desc: 千分位正则
 * @return {*}
 */
function formatNumber(num) {
  if (typeof num !== "number") {
    console.log("num is not a number");
    return;
  }
  return ("" + num).replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, "$1,");
}
/**
 * @name thousandth
 * @param {Number} resh
 * @desc 将传入数字转为千分位表示
 */
function thousandth(resh) {
  //小时用千分位表示
  if (resh >= 1000) {
    let arr = JSON.stringify(resh).split("");
    let resNum = "";
    let max = "";
    if (arr.length % 3 === 0) {
      resNum = averageArr(arr, 3);
    } else if (arr.length % 3 === 1) {
      max = arr[0];
      resNum = averageArr(arr.slice(1), 3);
    } else if (arr.length % 3 === 2) {
      max = arr.slice(0, 2);
      resNum = averageArr(arr.slice(2), 3);
    }
    //二维数组平铺展开为字符串，并消除','
    let str = resNum.reduce((per, cur, ind) => {
      if (ind + 1 === resNum.length) {
        let ss = cur.toString().replaceAll(",", "");
        per = per + ss;
        return per;
      } else {
        let ss = cur.toString().replaceAll(",", "");
        per = per + ss + ",";
        return per;
      }
    }, "");
    //首位判断
    if (max) {
      if (max.length > 0) {
        max = max.toString().replaceAll(",", "") + ",";
      } else {
        max = max + ",";
      }
    }
    return max + str;
  } else {
    return resh;
  }
}
/**
 * @name:  timeConvert
 * @param {Number} nums 时间,单位:s
 * @desc:  时间转换
 */
function timeConvert(nums) {
  if (!nums) {
    return "暂无数据";
  }
  const time = Number(nums);
  const min = 60; //一分
  const hour = 3600; //一小时
  let ress = ""; //s
  let resm = ""; //m
  let resh = ""; //h
  if (time <= min) {
    ress = time;
  } else if (time > min && time <= hour) {
    resm = Math.floor(time / min); //向下取整
    ress = time % min;
  } else {
    resh = Math.floor(time / hour);
    resm = Math.floor((time - resh * hour) / min);
    ress = time - resh * hour - resm * min;
  }
  let hourTime = resh > 0 ? resh + "小时" : "";
  let minTime = resm > 0 ? resm + "分钟" : "";
  let mioTime = ress > 0 ? ress + "秒" : "";

  if (resh >= 1000) {
    //千分位展示结果
    hourTime = thousandth(resh) + "小时";
  }

  return hourTime + minTime + mioTime;
}
/**
 * @name aveDis
 * @param {Number} total 分配总数
 * @param {Number} people 在线人数
 * @description 均分任务，剩余量从头分配
 */
function aveDis(total, people) {
  let surNum = total % people; //余数
  let baseNum = Math.floor(total / people); //商-向下取整
  let arr = [];
  for (let i = 0; i < people; i++) {
    arr.push(baseNum + (i < surNum ? 1 : 0));
  }
  return arr; //(3,5)=[1,1,1,0,0]
}
/**
 * @name setLocalStorage
 * @param {String} key 键值
 * @param {String/Object/Number} val 内容
 * @description 添加缓存
 */
function setLocalStorage(key, val = "") {
  //number判断特殊数字-0
  //val为真判断，防止null,undefined作为字符串存入
  let value = typeof val === "number" || val ? val : "";
  window.localStorage.setItem(`${key}`, JSON.stringify(value));
}
/**
 * @name getLocalStorage
 * @param {String} key 键值
 * @return 返回源数据
 * @description 获取对应键值的缓存
 */
function getLocalStorage(key) {
  let data = window.localStorage.getItem(`${key}`) || "";
  //JSON.parse无法对空字符串使用
  if (key && data) {
    data = JSON.parse(data);
  }
  return data;
}

/**
 * @name debounce
 * @param {Function} func 回调函数
 * @param {Number} delay 防抖周期
 */
let timeout = null;
function debounce(func, delay = 500) {
  if (!func) return;
  timeout && clearTimeout(timeout);
  timeout = setTimeout(() => {
    func();
  }, delay);
}

/**
 * @desc 滚动到指定元素
 * @param {string} containerId 容器元素id
 * @param {string} targetElementId 目标元素id
 * @param {number} offset 滚动偏移-例如边框宽度
 */

function scrollTo({ containerId = "", targetElementId = "", offset = 0 }) {
  try {
    if (!targetElementId) {
      return;
    }
    const container = containerId ? $(`#${containerId}`) : $("html,body");
    const target = $(`#${targetElementId}`);
    if (target.length > 0 && container.length > 0) {
      //容器元素离窗口顶部高度
      const parTop = container.offset().top;
      // 目标离浏览器窗口顶部高
      const childTop = target.offset().top;
      //滑动条滚动距离
      const scrollTop = container.scrollTop();
      //目标元素离容器元素顶部高-即容器元素滚动条所在高
      const top = childTop - parTop + scrollTop;
      container.animate({ scrollTop: top - offset });
    }
  } catch (err) {
    console.error(err);
  }
}
/**
 * @name scrollTops
 * @description 在规定时间返回顶部
 */
function scrollTops() {
  let times = 100; //返回顶部的时间-默认100ms,最大为500ms
  if (window) {
    times = window.scrollY > 500 ? 500 : window.scrollY;
    $("html,body").animate({ scrollTop: 0 }, times);
  }
}

export {
  proxys,
  objectToSearch,
  getSearchObject,
  randomNum,
  unitConver,
  averageArr,
  averageListArr,
  thousandth,
  timeConvert,
  aveDis,
  formatNumber,
  setLocalStorage,
  getLocalStorage,
  debounce,
  power,
  scrollTo,
  scrollTops
};
